<?php


namespace app\common\repositories\store\product;

use app\common\dao\store\product\ProductReplyTemplateDao;
use app\common\dao\store\StoreCategoryDao;
use app\common\repositories\BaseRepository;
use FormBuilder\Factory\Elm;
use think\facade\Db;
use think\facade\Route;



class ProductReplyTemplateRepository extends BaseRepository
{

    public function __construct(ProductReplyTemplateDao $dao)
    {
        $this->dao = $dao;
    }

    public function getList(array $where, $page, $limit)
    {
        $query = $this->dao->search($where)->with(['category']);
        $count = $query->count();
        $list = $query->page($page, $limit)->select();
        return compact('count', 'list');
    }

    public function save(array $data)
    {
        return Db::transaction(function () use($data){
            return $this->dao->create($data);
        });
    }

    public function edit($id, $data)
    {
        return $this->dao->update($id, $data);
    }

    public function detail(int $id)
    {
        $res = $this->dao->getWhere(['id'=>$id]);
        return $res;
    }


    public function getApiList($where, $page, $limit)
    {
        $query = $this->dao->search($where)->order('sort DESC,create_time DESC');
        $count = $query->count();
        $list = $query->page($page, $limit)->select();
        return compact(  'count',  'list');
    }


    public function form(?int $id = null )
    {
        $formData =[];
        if($id){
            $formData = $this->dao->get($id)->toArray();
        }

        $form = Elm::createForm(is_null($id) ? Route::buildUrl('systemProductReplyTemplateCreate')->build() : Route::buildUrl('systemProductReplyTemplateUpdate', ['id' => $id])->build());
        $form->setRule([
            Elm::cascader('cate_id', '顶级分类')->options(function () use ($id) {
                $menus = (new StoreCategoryDao())->getAllOptions(0,null,1,0);
                if ($id && isset($menus[$id])) unset($menus[$id]);
                $menus = formatCascaderData($menus, 'cate_name');
                return $menus;
            })->props(['props' => ['checkStrictly' => true, 'emitPath' => false]]),
            Elm::input('title', '标题')->required(),
            Elm::radio('lvl', '等级', 1)->options([['value' => 1, 'label' => '一般'],['value' => 2, 'label' => '很好']]),
            Elm::textarea('comment', '内容')->required(),
            Elm::number('sort', '排序', 0)->precision(0)->max(99999),
        ]);

        return $form->setTitle(is_null($id) ? '添加'  : '编辑')->formData($formData);
    }

}
